package com.sec.etech.org.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSONObject;
import com.sec.etech.org.dto.EtechUserDto;
import com.sec.etech.org.model.EtechUser;
import com.sec.etech.org.service.EtechGroupService;
import com.sec.etech.sys.msg.EtechMailService;
import com.sec.etech.sys.msg.model.EtechEmailMessage;
import com.sec.etech.sys.util.DbUtil;
import com.sec.etech.sys.util.PropertyUtil;
import org.openbpm.base.api.aop.annotion.CatchErr;
import org.openbpm.base.api.exception.BusinessException;
import org.openbpm.base.api.exception.BusinessMessage;
import org.openbpm.base.api.query.QueryFilter;
import org.openbpm.base.api.response.impl.ResultMsg;
import org.openbpm.base.core.encrypt.EncryptUtil;
import org.openbpm.base.core.util.StringUtil;
import org.openbpm.base.dao.CommonDao;
import org.openbpm.base.db.model.page.PageResult;
import org.openbpm.base.rest.util.RequestUtil;
import org.openbpm.org.core.manager.UserManager;
import org.openbpm.org.core.model.OrgRelation;
import org.openbpm.org.core.model.User;
import org.openbpm.org.rest.controller.UserController;
import org.openbpm.sys.util.ContextUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/etech/user")
public class EtechUserController extends UserController {

    @Resource
    UserManager userManager;
    @Resource
    EtechGroupService etechGroupService;

    @Resource
    EtechMailService etechMailService;

    public void sendPwdResetEmail(User user)
    {
        String content = user.getFullname() + "，您好：<br><br>&nbsp&nbsp您的ETech密码已重置为Stp." + user.getAccount() + "，请使用谷歌浏览器登录 <a href=\"http://etech.stcetech.ad01.sec.com/index.html\">ETech平台</a> 并及时修改密码。";
        EtechEmailMessage message = new EtechEmailMessage();

        message.setHtmlContent(content);
        message.setSubject("【密码重置提醒】");
        message.setTo(user.getId());

        etechMailService.sendMail(message);

    }

    @RequestMapping("resetPassword")
    @CatchErr("重置密码失败")
    public ResultMsg<String> resetPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = RequestUtil.getRQString(request, "id","当前用户ID");

        // TODO 检查是否有管理员权限
        if(!userId.equals(ContextUtil.getCurrentUserId())) {
            // throw new BusinessException("禁止修改他人密码！");
        }
        User user = userManager.get(userId);
        String newPassword = "Stp."+user.getAccount();
        user.setPassword(EncryptUtil.encryptSha256(newPassword));
        userManager.update(user);
        sendPwdResetEmail(user);
        return getSuccessResult("重置密码成功");
    }

    @RequestMapping("disabled")
    @CatchErr("禁用失败")
    public ResultMsg<String> disabledPassword(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = RequestUtil.getRQString(request, "id","当前用户ID");
        User user = userManager.get(userId);
        user.setStatus(0);
        userManager.update(user);
        return getSuccessResult("重置密码成功");
    }

    @RequestMapping("getDesigndprtidByUserId")
    @CatchErr("获取用户的设计科室失败")
    public ResultMsg<String> getDesigndprtidByUserId(@RequestParam(value = "userId", required = false) Long userId) throws Exception {
        if (userId == null) {
            return getSuccessResult(etechGroupService.getCurUserDesigndprtid());
        }
        return getSuccessResult(etechGroupService.getDesigndprtidByUserId(userId));
    }

    @RequestMapping({"listJson2"})
    public Object listJson2(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<EtechUserDto> users = new ArrayList<>();
        String keyword = RequestUtil.getString(request, "keyword").trim();
        String dprtName = RequestUtil.getString(request, "dprtName").trim();
        // 修改查询所有用户，包含已disable的帐号（含离职人员）
        String sql = "select t.id_ as id, t.fullname_ as fullname, t.account_ as account," +
                " t.email_ as email, t.mobile_ as mobile, t.sex_ as sex, " +
                " g.id_ as dprtid, g.name_ as dprtName," +
                " t.status_ as status, t.create_time_ as createTime " +
                " from org_user t " +
                " left join org_relation r on r.user_id_=t.id_ and r.type_='groupUser' and r.status_=1 and r.is_master_=1 " +
                " left join org_group g on r.group_id_=g.id_  " +
                " where t.id_>0 and t.account_>0";

        if(StringUtil.isNotEmpty(keyword)){
            sql += " and ( t.fullname_ like '%"+keyword+"%' or t.account_ like '%"+keyword+"' or t.email_ like '"+keyword+"%' or t.mobile_ like '%"+keyword+"' )";
        }
        if(StringUtil.isNotEmpty(dprtName)){
            sql += " and g.name_ like '%"+dprtName+"%'";
        }
        sql += " order by t.status_ desc, t.account_";
        sql += " limit 200";
        List<Map<String, Object>> list = DbUtil.getJdbcTemplate().queryForList(sql);
        if(list!=null && list.size()>0){
            for(Map<String, Object> row: list){
                EtechUserDto user = new EtechUserDto();
                user = conver2UserDto(user, row);
                users.add(user);
            }
        }
        JSONObject json = new JSONObject();
        json.put("rows", users);
        json.put("code","200");
        json.put("isOk",true);
        return  json;
        //return listJson(request, response);
    }

    public static EtechUserDto conver2UserDto(EtechUserDto user, Map<String, Object> row){
        if(user==null){
            user = new EtechUserDto();
        }
        if(row==null){
            return user;
        }
        BeanUtil.copyProperties(row, user);
        return user;
    }

    @RequestMapping({"get2"})
    @CatchErr
    public ResultMsg<EtechUserDto> get2(@RequestParam String id) throws Exception {
        User user1 = get(id).getData();
        EtechUserDto user = new EtechUserDto();
        BeanUtil.copyProperties(user1, user);
        String sql = "select * from org_users  where id_ = ?";
        List<Map<String, Object>> list = DbUtil.getJdbcTemplate().queryForList(sql, new Object[]{id});
        if(list!=null && list.size()>0){
            BeanUtil.copyProperties(list.get(0), user);
        }
        return ResultMsg.SUCCESS(user);
    }

    @RequestMapping("updateUserPhone")
    @CatchErr("更新分机失败")
    public ResultMsg<String> updateUserPhone(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String userId = RequestUtil.getRQString(request, "id","当前用户ID");
        String newPhone = RequestUtil.getRQString(request, "newPhone","新分机必填");
        //非管理员、人员角色管理员、系统开发人员角色只能修改自己的分机号
//        if (!ContextUtil.getCurrentUserId().equals(userId)
//                && !ContextUtil.currentUserIsAdmin()
//                && !EtechUserUtil.checkUserHasRole("HR_admin")
//                && !EtechUserUtil.checkUserHasRole("etech_dev")) {
//           return getWarnResult("对不起，您只能修改自己的分机号！");
//        }

        User user = userManager.get(userId);
        String phone = user.getMobile();
        if(newPhone.equals(phone)){
            throw new BusinessMessage("新分机必须同旧号码不一样");
        }
        user.setMobile(newPhone);
        user.setUpdateBy(ContextUtil.getCurrentUserId());
        user.setUpdateTime(new Date());
        userManager.update(user);
        return getSuccessResult("更新分机成功");

    }

    @Autowired
    CommonDao commonDao;

    @RequestMapping({"listJson3"})
    public PageResult listJson(HttpServletRequest request, HttpServletResponse response) throws Exception {
        QueryFilter queryFilter = this.getQueryFilter(request);
        String sql = "select id_ as id,fullname_ as fullname,account_ as account," +
                "email_ as email,mobile_ as mobile,weixin_ as weixin,address_ as address," +
                "sex_ as sex,status_ as status,create_time_ as createTime,create_by_ as createBy," +
                "update_by_ as updateBy,update_time_ as updateTime,remark_ as remark from org_user ";
        List pageList = commonDao.queryForListPage(sql, queryFilter);
        return new PageResult(pageList);
    }

    @RequestMapping({"listJson4"})
    public PageResult listJson4(HttpServletRequest request, HttpServletResponse response) throws Exception {
        QueryFilter queryFilter = this.getQueryFilter(request);
        String sql = "select a.id_ as id,a.fullname_ as fullname,a.account_ as account,\n" +
                "       a.email_ as email,a.mobile_ as mobile,a.weixin_ as weixin,a.address_ as address,\n" +
                "       a.sex_ as sex,a.status_ as status,a.create_time_ as createTime,a.create_by_ as createBy,\n" +
                "       a.update_by_ as updateBy, a.last_login as lastLogin,a.update_time_ as updateTime,a.remark_ as remark ,\n" +
                "        o.group_id_ as groupId\n" +
                "from org_user a\n" +
                "    left join org_relation o on (a.id_ = o.user_id_ and o.type_ = 'groupUser') ";
        List<Map<String, Object>> pageList = commonDao.queryForListPage(sql, queryFilter);
        pageList.parallelStream()
                .forEach(a -> {
                    String groupId = a.getOrDefault("groupId", "").toString();
                    a.put("groupFullName", etechGroupService.getFullGroupName(groupId));
                    // a.put("groupOrgRelations", etechGroupService.getOrgRelationByGroup(groupId));
                });
        return new PageResult(pageList);
    }


    @RequestMapping({"get3"})
    @CatchErr
    public ResultMsg<EtechUser> get3(@RequestParam String id) throws Exception {
        User user1 = get(id).getData();
        EtechUser user = new EtechUser();
        BeanUtil.copyProperties(user1, user);
        String sql = "select id_ as id,remark_ as remark from org_user  where id_ = ?";
        List<Map<String, Object>> list = DbUtil.getJdbcTemplate().queryForList(sql, new Object[]{id});
        if (list != null && list.size() > 0) {
            BeanUtil.copyProperties(list.get(0), user);
        }
        String groupId = "";
        if (user.getOrgRelationList() != null && user.getOrgRelationList().size() > 0){

            for (int i = 0; i < user.getOrgRelationList().size(); i++){
                if (user.getOrgRelationList().get(i).getIsMaster() != null && user.getOrgRelationList().get(i).getIsMaster().equals(1)){
                    groupId = user.getOrgRelationList().get(i).getGroupId();
                    if (groupId != null) {
                        break;
                    }
                }
            }
        }

        user.setGroupFullName(etechGroupService.getGroupFullName(groupId));
        user.setGroupOrgRelations(etechGroupService.getOrgRelationByGroup(groupId));
        user.setLastLogin(getLastLogin(id));
        user.setIsSignatured(getIsSignatured(id));
        return ResultMsg.SUCCESS(user);
    }

    public java.sql.Date getLastLogin(String userId) {
        String sql = "select last_login from org_user where id_ = ?";
        return DbUtil.getJdbcTemplate().queryForObject(sql, new Object[]{userId}, java.sql.Date.class);
    }

    public Boolean getIsSignatured(String userId) {
        String sql = "select is_signatured from org_user where id_ ='" + userId + "'";
        return DbUtil.getJdbcTemplate().queryForObject(sql, Boolean.class);
    }

    public EtechUser getUser(String id) throws Exception {
        User user1 = get(id).getData();
        EtechUser user = new EtechUser();
        BeanUtil.copyProperties(user1, user);
        user.setLastLogin(getLastLogin(id));
        user.setIsSignatured(getIsSignatured(id));
        return user;
    }

    @RequestMapping({"save3"})
    @CatchErr
    public ResultMsg<String> save3(@RequestBody EtechUser t) throws Exception {
        User user = new User();
        List<OrgRelation> orgRelationList = t.getOrgRelationList();
        int i=0;
        for (OrgRelation orgRelation : orgRelationList) {
            if (!StringUtil.isEmpty(orgRelation.getGroupName())){
                i++;
            }
        }
        for (OrgRelation orgRelation : orgRelationList) {
            if (i > 1 ||StringUtil.isEmpty(orgRelation.getGroupName())) {
                orgRelation.setIsMaster(0);
            } else orgRelation.setIsMaster(1);
        }
        BeanUtil.copyProperties(t, user);
        ResultMsg<String> resultMsg = this.save(user);
        if(resultMsg.getIsOk()){
            String sql = " update org_user set remark_ = ? where id_ = ? ";
            DbUtil.getJdbcTemplate().update(sql, t.getRemark(), t.getId());
        }
        return resultMsg;
    }

    @RequestMapping("updateUserPasswordProd")
    @CatchErr("更新密码失败")
    public ResultMsg<String> updateUserPasswordProd(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String account = RequestUtil.getRQString(request, "account","账号必填");
        String oldPassWorld = RequestUtil.getRQString(request, "oldPassword","旧密码必填");
        String newPassword = RequestUtil.getRQString(request, "newPassword","新密码必填");
        //String userId = RequestUtil.getRQString(request, "id","当前用户ID");

        User user = userManager.getByAccount(account);
        if(user==null || user.isDelete()){
            throw new BusinessException("用户不存在，请确认输入是否正确");
        }

        if (!user.getPassword().equals(EncryptUtil.encryptSha256(oldPassWorld))) {
            throw new BusinessMessage("旧密码输入错误");
        }

        user.setPassword(EncryptUtil.encryptSha256(newPassword));
        userManager.update(user);
        return getSuccessResult("更新密码成功");
    }
    @RequestMapping("getSystemEnv")
    @CatchErr("获取系统环境变量失败")
    public ResultMsg<String> getSystemEnv() throws Exception {
        String systemEnv = PropertyUtil.getPropertyService().getByAlias("systemEnvironmentVariables");
        return getSuccessResult(systemEnv);
    }
}
